
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from forms import userAdd


app = Flask(__name__)
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'm_datas'
USERNAME = 'root'
PASSWORD = ''
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(
    username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE
)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SECRET_KEY'] = '!@$$@#@$@#@!'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50))
    delete = db.Column(db.Integer)

@app.route('/')
def index():
    return render_template("base.html")

@app.route('/user_add', methods=['GET','POST'])
def user_add():
    form = userAdd()
    if request.method == 'POST':
        print('add user ...')
        u = User(name=form.username.data, delete='0')
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('user_show'))

    else:
        return render_template("add_user.html", form=form)


@app.route('/user_edit/int<uid>')
def user_edit(uid):
    form = userAdd()
    uid = uid
    u = User.query.filter(User.id == uid).first()
    return render_template("user_edit.html", u=u, form=form)


@app.route('/user_delete/int<uid>')
def user_delete(uid):
    uid = uid
    db.session.User.query.filter(User.id == uid).first().update({'delete': '0'})
    db.session.commit()
    return render_template("user_delete.html", uid=uid)

@app.route('/user_show')
def user_show():
    u_list = User.query.filter(User.delete==0).all()
    print(u_list)
    return render_template('user_show.html', u_list = u_list)

if __name__ == '__main__':
    app.run()


